﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;

namespace DimsMapper.Modules
{
    static class ProtoFiles
    {
        static readonly string[] protoPath = {
            "proto\\items\\",
            "proto\\critters\\",
            "proto\\scenery\\",
            "proto\\walls\\",
            "proto\\tiles\\",
            "proto\\misc\\"
        };

        // загруженные данные прототипов, ключ это индекс прототипа
        static Dictionary<int, Proto.Proto>[] protoList = new Dictionary<int, Proto.Proto>[6];

        public static void Initialization()
        {
            if (protoList[0] != null) return;

            for (int i = 0; i < 6; i++)
            {
                protoList[i] = new Dictionary<int, Proto.Proto>();
            }
        }

        public static void Clear()
        {
            for (int i = 0; i < 6; i++)
            {
                protoList[i].Clear();
            }   
        }

        public static int LoadProtoFile(Object.Types type, int index)
        {
            if (protoList[(int)type].ContainsKey(index)) return 0;

            string filename = protoPath[(int)type] + LstFiles.ProtoNameFile((int)type, index);
            DBFile file = DatFiles.OpenFile(filename);
            if (file == null) {
                // ошибка
                return -1;
            }

            protoList[(int)type].Add(index, new Proto.Proto(type, file));
            file.Close();
            return 1;
        }

        public static int LoadProtoFile(int pid)
        {
            Object.Types type = (Object.Types)(pid >> 24);
            int index = pid & 0xFFFF;

            return LoadProtoFile(type, index);
        }

        public static Proto.Proto GetProto(Object.Types type, int index)
        {
            if (LoadProtoFile(type, index) == -1) {
                return null; // ошибка
            }
            return protoList[(int)type][index];
        }

        public static Proto.Proto GetProto(int pid)
        {
            Object.Types type = (Object.Types)(pid >> 24);
            int index = pid & 0xFFFF;
            return GetProto(type, index);
        }

        public static int ProtoCount(Object.Types type)
        {
            return protoList[(int)type].Count;
        }

    }
}
